const app = getApp()
Page({
  onLoad() {
    var user = app.globalData.userInfo
    console.log('user', user)
    console.log('user.name', user.name)
    if (user && user.name) {
      this.setData({
        user: user,
        name: user.name,
        avatarUrl: user.avatarUrl
      })
    }
  },
  getName(e) {
    this.setData({
      name: e.detail.value
    })
  },
  //选择图片
  chooseImage() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sizeType: ['compressed'], //可以指定是原图还是压缩图，这里用压缩
      sourceType: ['album', 'camera'], //从相册选择
      success: (res) => {
        console.log("选择图片成功", res)
        this.setData({
          avatarUrl: res.tempFiles[0].tempFilePath
        })
      }
    })
  },
  //上传数据
  submit(e) {
    let user = this.data.user
    let filePath = this.data.avatarUrl
    let name = this.data.name
    if (filePath == user.avatarUrl && name == user.name) {
      console.log('头像姓名都没有改变')
    } else {
      wx.uploadFile({
        filePath: filePath,
        name: 'file',
        url: 'http://localhost:8080/api/user/edit',
        header: {
          "content-type": "multipart/form-data"
        },
        formData: {
          id: user.id,
          name: name
        },
        success: (res) => {
         
            console.log(res.data.msg)
            user.name = name,
              user.avatarUrl = filePath
            app._saveUserInfo(user)
            console.log("ok")
            wx.showToast({
              title: '修改成功',
              icon: "success"
            })
            wx.switchTab({
              url: '/pages/me/me',
          })
          
        }
      })

    }
  },
})